﻿using Microsoft.AspNetCore.Authorization;
using System.Threading.Tasks;

namespace Fast.Authorization
{
    /// <summary>
    /// 策略授权处理类
    /// </summary>
    [SkipScan]
    public abstract class FastAuthorizationHandler : IAuthorizationHandler
    {
        /// <summary>
        /// 授权处理方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task HandleAsync(AuthorizationHandlerContext context)
        {
            var isAuthenticated = context.User.Identity.IsAuthenticated;
            if (isAuthenticated)
            {
                if (await HandleNoneRequirementAsync(context))
                {
                    //获取尚未标记为成功的需求。
                    var pendingRequirements = context.PendingRequirements;

                    foreach (var requirement in pendingRequirements)
                    {
                        var handleResult = requirement is FastAuthorizationRequirement fastRequirement ?
                            await HandleFastRequirementAsync(context, fastRequirement) : await HandleRequirementAsync(context, requirement);

                        if (!handleResult)
                            break;
                        else
                            context.Succeed(requirement);  //将需求标记为成功
                    }
                    return;
                }
            }
            context.Fail();
        }
        /// <summary>
        /// 无策略授权处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public virtual Task<bool> HandleNoneRequirementAsync(AuthorizationHandlerContext context)
        {
            return Task.FromResult(true);
        }

        /// <summary>
        /// 框架策略授权处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public virtual Task<bool> HandleFastRequirementAsync(AuthorizationHandlerContext context, FastAuthorizationRequirement requirement)
        {
            return Task.FromResult(true);
        }

        /// <summary>
        /// 策略授权处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public virtual Task<bool> HandleRequirementAsync(AuthorizationHandlerContext context, IAuthorizationRequirement requirement)
        {
            return Task.FromResult(true);
        }
    }
}
